package com.example.server.manage.gptdialogue.server.listener;

import com.alibaba.fastjson.JSON;
import com.plexpt.chatgpt.listener.AbstractStreamListener;
import com.plexpt.chatgpt.util.SseHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.HashMap;
import java.util.Map;

/**
 * 描述：OpenAIEventSourceListener
 *
 * @author https:www.unfbx.com
 * @date 2023-02-22
 */
@Slf4j
@RequiredArgsConstructor
public class GPTEventSourceListener extends AbstractStreamListener {

    final SseEmitter sseEmitter;


    @Override
    public void onMsg(String message) {
        Map<String, String> messages = new HashMap<>();
        messages.put("content", message);
        SseHelper.send(sseEmitter, JSON.toJSONString(messages));
    }

    @Override
    public void onError(Throwable throwable, String response) {
        // 发送错误信息
        onMsg(response);
        SseHelper.complete(sseEmitter);
    }
}
